﻿using Microsoft.Extensions.DependencyInjection;
using WAU.Library.ObjectPool;
using RabbitMQChannel = RabbitMQ.Client.IModel;

namespace WAU.Library.RabbitMQ
{
    /// <summary>
    /// 池化 RabbitMQChannel 的扩展方法
    /// </summary>
    public static class PooledRabbitMQModelServiceCollectionExtension
    {
        /// <summary>
        /// AddRabbitMQConnectionPool
        /// </summary>
        /// <param name="services"></param>
        /// <param name="policy"></param>
        /// <param name="poolSize"></param>
        /// <returns></returns>
        public static IServiceCollection AddRabbitMQConnectionPool(
            this IServiceCollection services,
            PooledRabbitMQModelPolicy policy, int poolSize)
        {
            services.AddSingleton<SimpleRudeObjectPool<RabbitMQChannel>>((serviceProvier) =>
            {
                SimpleRudeObjectPoolProvider objectPoolProvider = new SimpleRudeObjectPoolProvider();
                objectPoolProvider.MaximumRetained = poolSize;
                return objectPoolProvider.Create(policy);
            });

            services.AddScoped<ScopedRabbitMQModelLease>();

            return services;
        }
    }
}
